package agi

import (
    "net/url"
    "net/http"
    "io/ioutil"
    "../logger"
)

func HttpGet(url string) (string, error) {
    resp, err := http.Get(url)
    if err != nil {
        logger.Debug("HttpGet", "请求错误:", err)
        return "", err
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        logger.Debug("HttpGet", "IO/Read错误:", err)
        return "", err
    }
    return string(body), err
}

func HttpPost(reqUrl string, post string) (string, error) {
    resp, err := http.PostForm(reqUrl, url.Values{"data": {post}})
    if err != nil {
        logger.Debug("HttpPost", "请求错误:", err)
        return "", err
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        logger.Debug("HttpPost", "IO/Read错误:", err)
        return "", err
    }
    return string(body), err
}

func HttpGetChan(url string, ch chan string) bool {
    resp, err := http.Get(url)
    if err != nil {
        logger.Debug("HttpGet", "请求错误:", err)
        ch <- ""
        return false
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        logger.Debug("HttpGet", "IO/Read错误:", err)
        ch <- ""
        return false
    }
    ch <- string(body)
    return true
}

func HttpPostChan(req string, post string, ch chan string) bool {
    resp, err := http.PostForm(req, url.Values{"data": {post}})
    if err != nil {
        logger.Debug("HttpPost", "请求错误:", err)
        ch <- ""
        return false
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        logger.Debug("HttpPost", "IO/Read错误:", err)
        ch <- ""
        return false
    }
    ch <- string(body)
    return true
}

